package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.OrderInfoService;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.SkuPriceVo;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-05-09
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private RemoteCartService remoteCartService;
    @Autowired
    private RemoteProductService productSkuService;
    @Autowired
    private RemoteUserAddressService remoteUserAddressService;
    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Override
    public TradeVo orderTradeData() {
        TradeVo tradeVo = new TradeVo();
        //远程调用购物车服务 获取商品类列表
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        //验证调用是否成功
        if(R.FAIL==cartCheckedList.getCode()){
            throw new RuntimeException("远程调用失败，失败原因:"+cartCheckedList.getMsg());
        }
        //获取到商品列表
        List<CartInfo> cartInfoList = cartCheckedList.getData();
        //将商品列表转为订单明细列表
        if(CollectionUtils.isEmpty(cartInfoList)){
            throw new SecurityException("购物车没有选中商品");
        }
        //购物车商品转为订单明细
        List<OrderItem> orderItemList =  cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo,orderItem);
            return orderItem;
        }).collect(Collectors.toList());
        tradeVo.setOrderItemList(orderItemList);
        //计算订单总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for(OrderItem orderItem:orderItemList){
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        tradeVo.setTotalAmount(totalAmount);
        //生成本次订单流水号避免重复点击提交  存入redis中五分钟过期时间
        String tradeNo = this.generateTradeNo();
        tradeVo.setTradeNo(tradeNo);


    //封装结果对象Vo相应返回给前端

        return tradeVo;
    }

    @Override
    public String generateTradeNo() {
        String tradeKey = "user:tradeNo:"+ SecurityContextHolder.getUserId();
        String tradeNo  = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(tradeKey,tradeNo,5*60);
        return tradeNo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //业务校验流水号避免重复提交 以及长时间停留订单超时
        String tradeKey = "user:tradeNo:" + SecurityContextHolder.getUserId();
        //通过Lua脚本验证流水号 KEYS[1]：流水号Key  ARGV[1]：用户提交流水号
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end\n";
        RedisScript<Boolean> booleanScript = new DefaultRedisScript<>(script,Boolean.class);
        Boolean fiag = (Boolean) redisTemplate.execute(booleanScript, Arrays.asList(tradeKey), orderForm.getTradeNo());
        if (!fiag){
            throw new SecurityException("流水号校验失败");
        }
        //验证订单明细商品价格是否变更
        //远程调用商品服务得到商品价格列表
        List<Long> skuIdList = orderForm.getOrderItemList().stream()
                .map(OrderItem::getSkuId)
                .collect(Collectors.toList());

        R<List<SkuPriceVo>> r = productSkuService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL==r.getCode()){
            throw new RuntimeException("远程调用失败，失败原因:"+r.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = r.getData();
        Map<Long,BigDecimal> sukPriceMap =
                skuPriceVoList.stream().collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        //如果商品价格有变更
        String priceErrorMsg = "";
        for (OrderItem orderItem : orderForm.getOrderItemList()) {
            if (orderItem.getSkuPrice().compareTo(sukPriceMap.get(orderItem.getSkuId())) != 0) {
                priceErrorMsg += orderItem.getSkuName() + "\n";
            }
        }
        if (StringUtils.isNotBlank(priceErrorMsg)){
            // 如果是通过购物车车途径提交订单，则远程调用"购物车服务"更新购物车中商品价格
            if (!orderForm.getIsBuy()) {
                remoteCartService.updateCartPrice(SecurityConstants.INNER);
            }
            //价格变更重新结算引导购物车页面
            throw new SecurityException("价格有变更，请重新结算！\n" + priceErrorMsg);
        }
        //如果没有变更  保存明细 日志
        Long orderId = this.saveOrder(orderForm);
        //TODO 锁定库存 基于mq

        //保存订单成功后， 如果是通过购物车车途径提交订单，清理用户购物车
        if (!orderForm.getIsBuy()) {
            remoteCartService.deleteCartCheckedList(SecurityConstants.INNER);
        }
        //7.响应订单ID，对接支付页面
        //TODO :RabbitMQ(死信、延迟插件)发送延迟消息 作用：自动将超时未支付订单关闭（延迟关单）
        return orderId;
    }

    @Override
    public Long saveOrder(OrderForm orderForm) {
        //保存订单信息
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        OrderInfo orderInfo = new OrderInfo();
        //用户信息
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        //生成订单编号  使用雪花算法生成订单编号
        String orderNo = DateUtils.getTime()+IdWorker.getIdStr();
        orderInfo.setOrderNo(orderNo);
        //便利订单明细计算从金额
        BigDecimal totalAmount = orderForm.getOrderItemList().stream()
                .map(OrderItem::getSkuPrice)
                //从0开始累加集合中的每一个元素
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setOriginalTotalAmount(totalAmount);
        //订单状态 待支付
        orderInfo.setOrderStatus(0);
        orderInfo.setCreateBy(userName);
        orderInfo.setRemark(orderForm.getRemark());
        //封装订单收件人信息 远程调用"用户服务"得到收件人信息
        R<UserAddress> r = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(),
                SecurityConstants.INNER);
        if (R.FAIL == r.getCode()){
            throw new RuntimeException("远程调用失败，失败原因:"+r.getMsg());
        }
        UserAddress userAddress = r.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getAddress());
        save(orderInfo);
        Long id = orderInfo.getId();
        //保存订单明细信息
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (!CollectionUtils.isEmpty(orderItemList)){
            for (OrderItem orderItem : orderItemList){
                orderItem.setOrderId(id);
                orderInfo.setCreateBy(userName);
                orderItemMapper.insert(orderItem);
            }
        }
        //保存订单操作日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(id);
        orderLog.setOperateUser(userId.toString());
        orderLog.setProcessStatus(0);
        orderLog.setNote(orderForm.getRemark());
        orderLog.setCreateBy(userName);
        orderLogMapper.insert(orderLog);
        return id;
    }

    @Override
    public TradeVo buy(Long skuId) {
        //创建订单确认vo对象
        TradeVo tradeVo = new TradeVo();
        //封装订单信息
        //远程调用商品服务得到商品信息
        R<ProductSkuVo> r = productSkuService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == r.getCode()){
            throw new RuntimeException("远程调用失败，失败原因:"+r.getMsg());
        }
        ProductSkuVo productSku = r.getData();

        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setSkuNum(1);
        List<OrderItem> orderItemList = Arrays.asList(orderItem);
        tradeVo.setOrderItemList(orderItemList);
        //封装订单价格
        tradeVo.setTotalAmount(productSku.getSalePrice());
        //生成流水号
        String string = this.generateTradeNo();
        tradeVo.setTradeNo(string);
        //设置立即购买为true
        tradeVo.setIsBuy(true);
        return tradeVo;
    }

    @Override
    public List<OrderInfo> userOrderInfoList(Integer orderStatus) {
        Long userId = SecurityContextHolder.getUserId();
        //查询订单信息
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<OrderInfo>()
                .eq(orderStatus!=null,OrderInfo::getOrderStatus, orderStatus)
                .eq(OrderInfo::getUserId, userId);
        List<OrderInfo> orderInfoList = list(queryWrapper);
        //查询订单明细信息将订单信息封装到订单明细信息中
        if (!CollectionUtils.isEmpty(orderInfoList)){
            List<Long> orderIdList = orderInfoList.stream().map(OrderInfo::getId).collect(Collectors.toList());
            LambdaQueryWrapper<OrderItem> orderItemLambdaQueryWrapper = new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIdList);
            List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemLambdaQueryWrapper);
            //为订单列表封装订单明细信息采用stream流
            Map<Long, List<OrderItem>> orderItemListMap =  orderItemList.stream().collect(
                    Collectors.groupingBy(OrderItem::getOrderId));
            for (OrderInfo orderInfo : orderInfoList){
                orderInfo.setOrderItemList(orderItemListMap.get(orderInfo.getId()));
            }
        }
        return orderInfoList;
    }

    @Override
    public String cancelOrder(Long orderId) {
        //根据订单ID查询订单信息
        OrderInfo orderInfo = getById(orderId);
        //判断订单状态如果是未支付才可取消
        if(orderInfo!=null && orderInfo.getOrderStatus()==0){
            orderInfo.setOrderStatus(-1);
            updateById(orderInfo);
        }
        //TODO 基于MQ解除锁定库存

        return null;
    }


}
